'use strict'
// 解析对象
import axios from 'axios'
import MD5 from '@/utils/md5'
import qs from 'qs'
// import VueCookies from 'vue-cookies'
let clientId = 'btcTFzRYswChNlQj'
let signType = 'MD5'
let charset = 'utf-8'
    // 需要唯一的一个标识
let secret = 'sLYKDJqPOXnsFcJVqlCUaR10FkPNMjaP'
let httpDomain = 'http://zgh.zg-weilaijia.com'
    // let httpDomain = 'http://192.168.1.122:7070'
    // 根据字典的key 排序
function transformObjKeySort(obj) {
    // 获取对象属性名字并按照字母顺序排列
    let arraykey = Object.keys(obj).sort()
    let str = []
    for (let p in arraykey) {
        str.push(arraykey[p] + '=' + obj[arraykey[p]])

    }
    return str.join('&')
}

function checkStatus(response) {
    // loading
    // 如果http状态码正常，则直接返回数据
    if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
        return response.data
            // 如果不需要除了data之外的数据，可以直接 return response.data
    }
    return {
        status: -404,
        msg: '网络异常'
    }
}

function checkCode(res) {
    // 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
    if (res.status === -404) {
        alert(res.msg)
    }
    if (res.data && (!res.data.success)) {
        alert(res.data.error_msg)
    }
    return res
}

export default {
    post(url, data) {
        data['clientId'] = clientId
        data['charset'] = charset
        // let accessToken = VueCookies.get('accessToken')
        // if(accessToken){
        //     data['accessToken'] = accessToken
        // } 
        // 时间戳
        data['reqTime'] = Date.parse(new Date())

        var params = transformObjKeySort(data)
        data['signType'] = signType
        var sign = MD5(params + secret)
        // var sign = MD5.hexMD5(params + secret)
        data['sign'] = sign

        return axios({
            method: 'post',
            baseURL: httpDomain,
            url,
            data: qs.stringify(data),
            timeout: 10000,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            responseType: 'json'
        }).then(
            (response) => {
                return checkStatus(response)
            }
        ).catch(
            (res) => {
                return checkCode(res)
            }
        )
    },
    get(url, params) {
        return axios({
            method: 'get',
            baseURL: httpDomain,
            url,
            params, // get 请求时带的参数
            timeout: 10000,
            headers: {
                // 'X-Requested-With': 'XMLHttpRequest'
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            responseType: 'json'
        }).then(
            (response) => {
                return checkStatus(response)
            }
        ).catch(
            (res) => {
                return checkCode(res)
            }
        )
    }
}